package cn.edu.dlut.port.isp.profile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.edu.dlut.port.isp.config.PictureUploadProperties;

@Controller
public class PictureUploadController {
	private Resource picdir;
	private Resource anonymousPic;
	private MessageSource messageSource;
	private UserProfileSession userProfileSession;

	@Autowired
	public PictureUploadController(PictureUploadProperties pictureUploadProperties, MessageSource messageSource,
			UserProfileSession userProfileSession) {
		picdir = pictureUploadProperties.getUploadPath();
		anonymousPic = pictureUploadProperties.getAnonymousPicture();
		this.messageSource = messageSource;
		this.userProfileSession = userProfileSession;
	}

	@RequestMapping("/upload")
	public String uploadPage() {
		return "profile/upload";
	}

	@RequestMapping(value = "/register", params = { "upload" }, method = RequestMethod.POST)
	public String onUpload(@RequestParam MultipartFile file, RedirectAttributes redirectAttrs) throws IOException {

		if (file.isEmpty() || !isImage(file)) {
			redirectAttrs.addFlashAttribute("error", "Incorrect file. Please upload a picture.");
			return "redirect:/register";
		}

		Resource picturePath = copyFileToPictures(file);
		System.out.println(picturePath.getFilename());
		userProfileSession.setPicturePath(picturePath);
		System.out.println(userProfileSession.getPicturePath().toString());
		return "redirect:register";
	}

	@RequestMapping(value = "/uploadedPicture")
	public void getUploadedPicture(HttpServletResponse response) throws IOException {
		Resource picturePath = userProfileSession.getPicturePath();
		System.out.println(picturePath==null);
		if (picturePath == null) {
			picturePath = anonymousPic;
		}
		response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(picturePath.getFilename()));
		IOUtils.copy(picturePath.getInputStream(), response.getOutputStream());
	}

	@ExceptionHandler(IOException.class)
	public ModelAndView handleIOException(Locale locale) {
		ModelAndView modelAndView = new ModelAndView("profile/register");
		modelAndView.addObject("error", messageSource.getMessage("upload.io.exception", null, locale));
		modelAndView.addObject("profileForm", userProfileSession.toForm());
		return modelAndView;
	}

	@RequestMapping("uploadError")
	public ModelAndView onUploadError(Locale locale) {
		ModelAndView modelAndView = new ModelAndView("profile/upload");
		// modelAndView.addObject("error",
		// messageSource.getMessage("upload.file.too.big", null, locale));
		modelAndView.addObject("error", "file is too big.");
		return modelAndView;
	}

	private boolean isImage(MultipartFile file) {
		// TODO Auto-generated method stub
		return file.getContentType().startsWith("image");
	}

	private Resource copyFileToPictures(MultipartFile file) throws IOException {
		String filename = file.getOriginalFilename();
		File tempFile = File.createTempFile("pic", getFileExtension(filename), picdir.getFile());
		try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile)) {
			IOUtils.copy(in, out);
		}
		return new FileSystemResource(tempFile);

	}

	private String getFileExtension(String filename) {
		return filename.substring(filename.lastIndexOf("."));
	}
	
}
